package sim1011.behaviours;

import sim1011.poltergeist.ResourceManager;
import sim1011.starter.EctoMobileStarter;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

public class ConsumeResourceBehaviour extends OneShotBehaviour {
	private static final long serialVersionUID = 306100760640873970L;
	private int reqCPU;
	private int reqMEM;
	private AID sender;

	public ConsumeResourceBehaviour(int reqCPU, int reqMEM, AID aid) {
		this.reqCPU = reqCPU;
		this.reqMEM = reqMEM;
		this.sender = aid;
	}

	@Override
	public void action() {
		((ResourceManager) myAgent).consumeResource(reqCPU, reqMEM);
		((ResourceManager) myAgent).setBatteryLevel(((ResourceManager) myAgent)
				.getBatteryLevel()
				- ((ResourceManager) myAgent).consumeBatteryOnExecution(reqCPU,
						reqMEM));
		try {
			Thread.sleep(this.getExecutionTime(reqCPU, reqMEM));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		((ResourceManager) myAgent).releaseResource(reqCPU, reqMEM);
		sendFinishedExecution();
	}

	private long getExecutionTime(int reqCPU2, int reqMEM2) {
		return EctoMobileStarter.r.nextInt(2000);
	}

	private void sendFinishedExecution() {
		ACLMessage sendAck = new ACLMessage(ACLMessage.DISCONFIRM);
		sendAck.addReceiver(sender);
		myAgent.send(sendAck);
	}
}
